<template>
  <div class="chart-wrapper">
    <h3>地区销售排行</h3>
    <v-chart class="chart" :option="option" autoresize />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { use } from 'echarts/core'
import { BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import VChart from 'vue-echarts'
import type { EChartsOption } from 'echarts'
import http from '../http.js'

use([
  CanvasRenderer,
  BarChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
])

const option = ref<EChartsOption>({})

onMounted(async () => {
  // 1. 请求数据
  const res = await http.get('/rank.json')
  // 2. 按 value 排序，取前10名
  const top10 = res.sort((a: any, b: any) => b.value - a.value).slice(0, 10)
  const xAxisData = top10.map((item: any) => item.name)
  const seriesData = top10.map((item: any) => item.value)

  // 3. 组装 option
  option.value = {
    grid: {
      left: '5%',
      right: '5%',
      top: '10%',
      bottom: '10%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#ffffff30'
        }
      },
      axisLabel: {
        color: '#fff',
        interval: 0,
        rotate: 0
      }
    },
    yAxis: {
      type: 'value',
      // max: 180, // 可根据数据动态调整
      // interval: 30,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#ffffff30'
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#ffffff10'
        }
      },
      axisLabel: {
        color: '#fff'
      }
    },
    series: [
      {
        type: 'bar',
        data: seriesData,
        barWidth: '40%',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: '#9D4EDD'
            }, {
              offset: 1,
              color: '#4B79E5'
            }]
          }
        }
      }
    ]
  }
})
</script>

<style scoped>
.chart-wrapper {
  width: 100%;
  height: 100%;
  padding: 12px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

h3 {
  color: #fff;
  font-size: 16px;
  margin: 0 0 10px 0;
  padding-left: 10px;
}

.chart {
  flex: 1;
  width: 100%;
}
</style>
